<template>
    <div style="text-align:left;">

        <!--路径-->
        <div class="row-box">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>权限管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <!--操作按钮-->
        <div class="row-box">
            <el-input size="medium" placeholder="请输入登录名" class="txt" />
            <el-button size="medium">查询</el-button>
            <el-button size="medium" @click="dialogEdit">添加用户</el-button>
            <el-button size="medium" @click="eventDelete('')">批量删除</el-button>
            <el-button size="medium">批量禁用</el-button>
            <el-button size="medium" @click="dialogEmployeeVisible = true">批量导入</el-button>
            <el-button size="medium">批量导出</el-button>
        </div>

        <!--列表-->
        <div class="row-box">
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="登录名" prop="loginName"></el-table-column>
                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)">编辑角色</el-button>
                        <el-button size="mini" type="danger" @click="eventDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!--分页-->
        <div class="row-box">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page.sync="pages.pageIndex" :page-size="pages.pageSize" layout="total, prev, pager, next"
                :total="pages.total">
            </el-pagination>
        </div>



        <!--弹出对话框-->
        <div>

            <!--编辑用户对话框-->
            <el-dialog title="编辑用户" :visible.sync="dialogFormVisible">
                <el-form :model="form">
                    <el-form-item label="用户名称" :label-width="formLabelWidth">
                        <el-input v-model="form.name" :disabled="disabled" autocomplete="off"></el-input>
                    </el-form-item>

                    <el-form-item label="选择角色" :label-width="formLabelWidth">
                        <el-checkbox-group v-model="checkList">
                            <el-checkbox v-for="(item, index) in roleData" :key="index" :label="item.id">{{ item.name
                            }}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="eventSubmit">确 定</el-button>
                </div>
            </el-dialog>

            <!--导入数据-->
            <el-dialog title="导入员工" :visible.sync="dialogEmployeeVisible">
                <div>
                    <el-upload class="upload-demo" ref="upload" action="http://localhost:5148/rbac/user/import"
                        :on-preview="handlePreview" :on-remove="handleRemove" :on-success="uploadSuccess"
                        :file-list="fileList" :auto-upload="false">
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <el-button style="margin-left: 10px;" size="small" type="success"
                            @click="submitUpload">上传到服务器</el-button>
                        <span style="margin-left:50px;" @click="eventDownloadTemplate">下载模板文件</span>
                    </el-upload>
                </div>
            </el-dialog>
        </div>

    </div>
</template>

<script>
export default {
    data() {
        return {
            tableData: [],
            checkList: [],
            userId: '',

            dialogFormVisible: false,
            dialogEmployeeVisible: false,
            fileList: [],
            form: {
                name: '',
            },
            disabled: false,
            formLabelWidth: '120px',
            //角色数据列表
            roleData: [],
            pages: {
                pageIndex: 1,
                pageSize: 10,
                total: 0
            },
            multipleSelection: []
        };
    },
    mounted() {
        this.onLoadData()
    },
    methods: {
        //下载模板文件
        eventDownloadTemplate() {
            let url = 'http://localhost:5148/rbac/user/download'
            this.$http.post(url,{
                'responseType':'arrayBuffer'
            }).then(res => {
                console.log(res)
                const blob = new Blob([res.data],{type:'application/vnd.ms-excel;charset=utf-8'})
                const url = window.URL.createObjectURL(blob);
                this.download(url)
            })
        },
        //下载文件
        download(url) {
            const a = document.createElement('a');
            a.style.display = 'none';
            a.download = '人员信息导入模板.xlsx';
            a.href = url;
            a.click();
            document.body.removeChild(a)
            window.URL.revokeObjectURL(url)
        },
        //上传按钮
        submitUpload() {
            this.$refs.upload.submit();
        },
        //上传成功
        uploadSuccess(response) {
            console.log(response)
            if (response.code == 200) {
                this.dialogEmployeeVisible = false
                this.onLoadData()
            }
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //批量删除
        eventDelete(id) {
            let url = this.$baseUrl + '/rbac/user'

            //要得到想删除的id
            let data = []

            if (id == '') {
                this.multipleSelection.forEach(x => {
                    data.push({ id: x.id })
                })
            } else {
                data.push({ id: id })
            }
            this.$http.delete(url, { data: data })
                .then(res => {
                    if (res.data.code == 200) {
                        this.onLoadData()
                        this.$message.info(res.data.message)
                    } else {
                        this.$message.error(res.data.message)
                    }
                })
                .catch(err => {
                    if (err == 'ERR_NETWORK') {
                        this.$message.error('网络连接出错啦')
                    }
                })
        },
        handleEdit(row) {
            this.dialogFormVisible = true;
            this.userId = row.id
            this.form.name = row.loginName
            this.disabled = true
            this.onLoadRoleList()
            this.onLoadUserRoleByUserId(row.id)
        },
        onLoadUserRoleByUserId(userId) {
            let url = this.$baseUrl + '/rbac/user/byid'
            this.$http.get(url, {
                params: {
                    userId: userId
                }
            }).then(res => {
                console.log(res)

                //把这些拥有的角色反填到角色列表上
                this.checkList = res.data.data

            })
        },
        //加载角色列表
        onLoadRoleList() {
            let url = this.$baseUrl + '/role'
            this.$http.get(url, {
                params: {
                    pageIndex: 1,
                    pageSize: 200
                }
            }).then(res => {
                this.roleData = res.data.data.items
            })
        },
        onLoadData() {
            let url = this.$baseUrl + '/rbac/User'
            this.$http.get(url, {
                params: {
                    pageIndex: 1,
                    pageSize: 20
                },
                headers: {
                    'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODI2ODMxNjcsImlzcyI6Imh0dHA6Ly93d3cuMjAwOWEuY29tIiwiYXVkIjoiYXV0aG9yIn0.Ncy0MBOYgEU69ND_4Ujy3cGeD1i3UDl-QWVeQ8RgHV0'
                }
            }).then(res => {
                this.tableData = res.data.result
            })
        },
        eventSubmit() {
            //获取输入用户名
            //console.log('用户名：' + this.form.name)
            //获取选中的角色
            //console.log(this.checkList)

            //将用户名和选中的角色传递给后台
            let url = this.$baseUrl + '/rbac/user/ur'
            let data = {
                "userId": this.userId,
                "loginName": this.form.name,
                "rolesId": this.checkList
            }
            this.$http.post(url, data).then(res => {
                console.log(res)
                if (res.data.code == 200) {
                    this.dialogFormVisible = false
                    this.onLoadData()
                }
            })
        },
        dialogEdit() {
            this.dialogFormVisible = true
            this.onLoadRoleList()
            this.disabled = false

            this.userId = ''
            this.form.name = ''
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
        }
    }
};
</script>

<style scoped>
.txt {
    width: 180px;
}

.row-box {
    margin-bottom: 20px;
}
</style>